<template>
  <div class="user-management-page">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="actions">
            <el-button type="primary" :icon="Plus" @click="handleAddUser">添加用户</el-button>
            <el-button type="success" :icon="Refresh" @click="handleRefresh">刷新列表</el-button>
          </div>
        </div>
      </template>

      <div class="search-container">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable @keyup.enter="handleSearch" style="width: 200px" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable @keyup.enter="handleSearch" style="width: 200px" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="searchExpanded" label="用户类型">
            <el-select v-model="searchForm.userType" placeholder="请选择用户类型" clearable style="width: 200px">
              <el-option label="管理员" :value="1" />
              <el-option label="普通用户" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
            <el-button type="text" @click="toggleSearchExpanded">
              {{ searchExpanded ? '收起' : '更多' }}
              <el-icon><component :is="searchExpanded ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-container">
        <el-table :data="userList" v-loading="loading" border empty-text="暂无用户数据" height="100%">
          <el-table-column prop="username" label="用户名" min-width="120" />
          <el-table-column prop="nickname" label="昵称" min-width="120" />
          <el-table-column prop="email" label="邮箱" min-width="200" />
          <el-table-column prop="phone" label="手机号" min-width="140" />
          <el-table-column prop="userType" label="用户类型" width="120">
            <template #default="{ row }">
              <el-tag :type="row.userType === 1 ? 'danger' : 'primary'">
                {{ row.userType === 1 ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastLoginTime" label="最后登录时间" width="180">
            <template #default="{ row }">{{ formatDateTime(row.lastLoginTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="380" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
                <el-button type="warning" size="small" :icon="Setting" @click="handleAssignRoles(row)">分配角色</el-button>
                <el-button type="info" size="small" :icon="Key" @click="handleResetPassword(row)">重置密码</el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)" :disabled="row.userType === 1">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Dialogs -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @close="handleDialogClose">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="userForm.userType">
            <el-radio :value="1">管理员</el-radio>
            <el-radio :value="2">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">{{ isEdit ? '更新' : '创建' }}</el-button>
      </template>
    </el-dialog>

    <el-dialog title="分配角色" v-model="roleDialogVisible" width="500px" @close="handleRoleDialogClose">
      <el-checkbox-group v-model="selectedRoleIds">
        <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoles" :loading="roleSubmitting">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Refresh, Search, Edit, Delete, Setting, Key, ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import { getUserListApi, createUserApi, updateUserApi, deleteUserApi, getUserRolesApi, assignUserRolesApi } from '@/api/user';
import { getRoleListApi } from '@/api/role';

// Interfaces
interface User {
  id?: number;
  username: string;
  nickname?: string;
  password?: string;
  email?: string;
  phone?: string;
  status: number;
  userType: number;
  lastLoginTime?: string;
  createTime?: string;
  updateTime?: string;
}

interface Role {
  id: number;
  roleName: string;
}

// Reactive state
const loading = ref(false);
const submitting = ref(false);
const roleSubmitting = ref(false);
const userList = ref<User[]>([]);
const allRoles = ref<Role[]>([]);
const dialogVisible = ref(false);
const roleDialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const userFormRef = ref();
const currentUser = ref<User | null>(null);
const selectedRoleIds = ref<number[]>([]);

const searchForm = ref({
  username: '',
  email: '',
  status: undefined as number | undefined,
  userType: undefined as number | undefined,
});

const searchExpanded = ref(false);

const userForm = ref<User>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  status: 1,
  userType: 2,
});

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
};

// Computed properties - 移除前端筛选，直接使用后端返回的数据

// Methods
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  userForm.value = {
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    status: 1,
    userType: 2,
  };
};

const fetchUserList = async (searchParams?: any) => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      ...searchParams
    };
    const res = await getUserListApi(params);
    userList.value = Array.isArray(res) ? res : (res.records || res);
    // 如果后端返回分页信息，更新总数
    if (res.total !== undefined) {
      pagination.value.total = res.total;
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchAllRoles = async () => {
  try {
    const res = await getRoleListApi();
    // 兼容后端直接返回数组
    allRoles.value = Array.isArray(res) ? res : (res.data || res);
  } catch (error) {
    ElMessage.error('获取角色列表失败');
  }
};

onMounted(() => {
  fetchUserList();
  fetchAllRoles();
});

const handleSearch = () => {
  pagination.value.currentPage = 1;
  const searchParams = {
    username: searchForm.value.username || undefined,
    email: searchForm.value.email || undefined,
    status: searchForm.value.status,
    userType: searchForm.value.userType
  };
  fetchUserList(searchParams);
};

const handleReset = () => {
  searchForm.value = {
    username: '',
    email: '',
    status: undefined,
    userType: undefined,
  };
  pagination.value.currentPage = 1;
  fetchUserList();
};

const toggleSearchExpanded = () => {
  searchExpanded.value = !searchExpanded.value;
};

const handleRefresh = () => {
  fetchUserList();
};

const handleAddUser = () => {
  resetForm();
  isEdit.value = false;
  dialogTitle.value = '添加用户';
  dialogVisible.value = true;
};

const handleEdit = (user: User) => {
  resetForm();
  isEdit.value = true;
  dialogTitle.value = '编辑用户';
  Object.assign(userForm.value, user);
  dialogVisible.value = true;
};

const handleDelete = (user: User) => {
  ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteUserApi(user.id!);
      ElMessage.success('删除成功');
      fetchUserList();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

const handleResetPassword = (user: User) => {
  ElMessageBox.confirm(`确定要重置用户 "${user.username}" 的密码吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // TODO: 调用重置密码API
      ElMessage.success('密码重置成功，新密码已发送至用户邮箱');
    } catch (error) {
      ElMessage.error('密码重置失败');
    }
  });
};

const handleDialogClose = () => {
  resetForm();
};

const handleSubmit = () => {
  userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitting.value = true;
      try {
        if (isEdit.value) {
          await updateUserApi(userForm.value.id!, userForm.value);
          ElMessage.success('更新成功');
        } else {
          await createUserApi(userForm.value);
          ElMessage.success('创建成功');
        }
        dialogVisible.value = false;
        fetchUserList();
      } catch (error) {
        // ElMessage.error(isEdit.value ? '更新失败' : '创建失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

const handleAssignRoles = async (user: User) => {
  currentUser.value = user;
  roleDialogVisible.value = true;
  try {
    const res = await getUserRolesApi(user.id!);
    // 后端返回的是角色ID数组，不是角色对象数组
    selectedRoleIds.value = res.data || [];
  } catch (error) {
    ElMessage.error('获取用户角色失败');
  }
};

const handleRoleDialogClose = () => {
  selectedRoleIds.value = [];
  currentUser.value = null;
};

const handleSaveRoles = async () => {
  if (!currentUser.value) return;
  roleSubmitting.value = true;
  try {
    await assignUserRolesApi(currentUser.value.id!, selectedRoleIds.value);
    ElMessage.success('分配角色成功');
    roleDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('分配角色失败');
  } finally {
    roleSubmitting.value = false;
  }
};

const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  handleSearch();
};

const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page;
  handleSearch();
};
</script>

<style lang="less" scoped>
.user-management-page {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.main-card {
  height: 100%;
  display: flex;
  flex-direction: column;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  :deep(.el-card__header) {
    flex-shrink: 0;
  }

  :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    padding: 20px;
  }
}

.search-container {
  flex-shrink: 0;
  margin-bottom: 16px;
}

.table-container {
  flex: 1;
  min-height: 0;
  overflow: hidden; /* For el-table height="100%" to work */
}

.pagination-container {
  flex-shrink: 0;
  padding-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: nowrap;
  
  .el-button {
    margin-left: 0;
    margin-right: 0;
    padding: 5px 8px;
    font-size: 12px;
  }
}
</style>